package services

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/component"
	"pitaya_new_chatroom/i18n"
	"pitaya_new_chatroom/manager/global"
	"pitaya_new_chatroom/manager/userSession"
	"pitaya_new_chatroom/protos"
	"pitaya_new_chatroom/utils"
)

// handler 结构体必须继承一下 Base 类
type Connector struct {
	component.Base
}

type ConnectorRemote struct {
	component.Base
}

//返回session里的data数据
func (c *Connector) GetSessionData(ctx context.Context) (*protos.SessionDataResponse,error) {

	s := pitaya.GetSessionFromCtx(ctx)
	data := s.GetData()
	respond:=&protos.SessionDataResponse{}
	respond.Code = 20
	byteData,_:=json.Marshal(data)
	respond.Data = byteData
	return respond,nil
}

// 需要一个login 绑定下连接的生命周期函数

func (c *Connector) Login(ctx context.Context,data *protos.Login)(*protos.RequestRes,error){
	fmt.Println("login data",data.Nickname)
	s := pitaya.GetSessionFromCtx(ctx)
	l := pitaya.GetDefaultLoggerFromCtx(ctx)
	var info *userSession.SessionInfo
	sessionID,info,_:= global.G.UserSession.GetUserSession(data.Nickname)
	// 没有登录过

	if sessionID == "" && info == nil{
		sessionId,_ :=global.G.UserSession.CreateUserSession(data.Nickname)
		info=&userSession.SessionInfo{Nickname:data.Nickname}
		info.UID = data.Nickname
		global.G.UserSession.StoreUserSession(sessionId,info)

	}else{
		//已经登录
		fmt.Println("已经登录过了",info,info.RoomId)
		s.Bind(ctx, info.UID)
	}

	// 新连接 或者 重连进来的 可以能需要新或者重新绑一次 
	if s.UID() == "" {
		s.Bind(ctx,data.Nickname)
	}
	if s.Get("backendServerId")==nil && s.Get("roomId")==nil {
		s.SetData(map[string]interface{}{
			"roomId":info.RoomId,
			"backendServerId": info.BackendServerId,
		})
	}


	s.OnClose(func(){
		backendServerId:= info.BackendServerId
		reqData:=make(map[string]interface{})
		roomId := info.RoomId
		if backendServerId == "" {
			return
		}

		reqData["uid"] = info.UID
		reqData["roomId"] = roomId
		reqDataStr,_:=json.Marshal(reqData)
		ret := &protos.RPCRes{}
		args:=&protos.RPCReq{Msg:string(reqDataStr)}

		err:=pitaya.RPCTo(ctx,backendServerId,"room.backend.usersessionclose",ret,args)

		if err != nil {
			// 错误code 可以要处理下 记一下日志之类的

			l.Error(pitaya.Error(err,"RPC-001"))

		}else{
			fmt.Printf("远程rpc结果：%v",ret)
			if ret.Code == 200 && roomId != ""{
				msg:=make(map[string]string,0)
				json.Unmarshal([]byte(ret.Msg),&msg)
				pitaya.GroupBroadcast(
					ctx,
					"chatroom",
					roomId,
					"onLeaveUser",
					utils.Utils.ReturnComplexData("leaveUserNotify",200, map[string]interface{}{

						"content":i18n.I18n.GetText(ctx,fmt.Sprintf("用户[%s]离开房间",msg["Username"])),
					}),
				)
			}else{
				l.Errorf("房间服务器清除用户数据异常：%v",ret)
			}

		}
	})

	return utils.Utils.ReturnComplexData("loginRespond", 200,&protos.LoginRes{Msg: "登录成功",RoomId:info.RoomId,NickName: info.Nickname}),nil
}



func (c *ConnectorRemote) RemoteFunc(ctx context.Context,msg *protos.RPCReq) (*protos.RPCRes,error){
	fmt.Println("远程rpc 会调用 chatroom.connector.remoteFunc 来进行通知")
	res:=&protos.RPCRes{}
	return res ,nil
}


func (c *ConnectorRemote) UpdateLocation(ctx context.Context,msg *protos.RPCReq) (*protos.RPCRes,error){
	fmt.Println("更新位置")

	m:=make(map[string]string)
	json.Unmarshal([]byte(msg.Msg),&m)

	sessionID,info,_:= global.G.UserSession.GetUserSession(m["nickName"])

	fmt.Println(sessionID,info)
	if sessionID !="" && info != nil{
		info.Nickname = m["nickName"]
		info.BackendServerId = m["backendServerId"]
		info.RoomId = m["roomId"]
		global.G.UserSession.StoreUserSession(sessionID,info)
		fmt.Println("更新位置完成")
	}

	res:=&protos.RPCRes{}
	return res ,nil
}